home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.5 / urllib2.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-05-11  |  40.7 KB  |  1,346 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''An extensible library for opening URLs using a variety of protocols
  5.  
  6. The simplest way to use this module is to call the urlopen function,
  7. which accepts a string containing a URL or a Request object (described
  8. below).  It opens the URL and returns the results as file-like
  9. object; the returned object has some extra methods described below.
  10.  
  11. The OpenerDirector manages a collection of Handler objects that do
  12. all the actual work.  Each Handler implements a particular protocol or
  13. option.  The OpenerDirector is a composite object that invokes the
  14. Handlers needed to open the requested URL.  For example, the
  15. HTTPHandler performs HTTP GET and POST requests and deals with
  16. non-error returns.  The HTTPRedirectHandler automatically deals with
  17. HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
  18. deals with digest authentication.
  19.  
  20. urlopen(url, data=None) -- basic usage is the same as original
  21. urllib.  pass the url and optionally data to post to an HTTP URL, and
  22. get a file-like object back.  One difference is that you can also pass
  23. a Request instance instead of URL.  Raises a URLError (subclass of
  24. IOError); for HTTP errors, raises an HTTPError, which can also be
  25. treated as a valid response.
  26.  
  27. build_opener -- function that creates a new OpenerDirector instance.
  28. will install the default handlers.  accepts one or more Handlers as
  29. arguments, either instances or Handler classes that it will
  30. instantiate.  if one of the argument is a subclass of the default
  31. handler, the argument will be installed instead of the default.
  32.  
  33. install_opener -- installs a new opener as the default opener.
  34.  
  35. objects of interest:
  36. OpenerDirector --
  37.  
  38. Request -- an object that encapsulates the state of a request.  the
  39. state can be a simple as the URL.  it can also include extra HTTP
  40. headers, e.g. a User-Agent.
  41.  
  42. BaseHandler --
  43.  
  44. exceptions:
  45. URLError-- a subclass of IOError, individual protocols have their own
  46. specific subclass
  47.  
  48. HTTPError-- also a valid HTTP response, so you can treat an HTTP error
  49. as an exceptional event or valid response
  50.  
  51. internals:
  52. BaseHandler and parent
  53. _call_chain conventions
  54.  
  55. Example usage:
  56.  
  57. import urllib2
  58.  
  59. # set up authentication info
  60. authinfo = urllib2.HTTPBasicAuthHandler()
  61. authinfo.add_password(\'realm\', \'host\', \'username\', \'password\')
  62.  
  63. proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})
  64.  
  65. # build a new opener that adds authentication and caching FTP handlers
  66. opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)
  67.  
  68. # install it
  69. urllib2.install_opener(opener)
  70.  
  71. f = urllib2.urlopen(\'http://www.python.org/\')
  72.  
  73.  
  74. '''
  75. import base64
  76. import hashlib
  77. import httplib
  78. import mimetools
  79. import os
  80. import posixpath
  81. import random
  82. import re
  83. import socket
  84. import sys
  85. import time
  86. import urlparse
  87. import bisect
  88.  
  89. try:
  90.     from cStringIO import StringIO
  91. except ImportError:
  92.     from StringIO import StringIO
  93.  
  94. from urllib import unwrap, unquote, splittype, splithost, quote, addinfourl, splitport, splitgophertype, splitquery, splitattr, ftpwrapper, noheaders, splituser, splitpasswd, splitvalue
  95. from urllib import localhost, url2pathname, getproxies
  96. __version__ = sys.version[:3]
  97. _opener = None
  98.  
  99. def urlopen(url, data = None):
  100.     global _opener
  101.     if _opener is None:
  102.         _opener = build_opener()
  103.     
  104.     return _opener.open(url, data)
  105.  
  106.  
  107. def install_opener(opener):
  108.     global _opener
  109.     _opener = opener
  110.  
  111.  
  112. class URLError(IOError):
  113.     
  114.     def __init__(self, reason):
  115.         self.args = (reason,)
  116.         self.reason = reason
  117.  
  118.     
  119.     def __str__(self):
  120.         return '<urlopen error %s>' % self.reason
  121.  
  122.  
  123.  
  124. class HTTPError(URLError, addinfourl):
  125.     '''Raised when HTTP error occurs, but also acts like non-error return'''
  126.     __super_init = addinfourl.__init__
  127.     
  128.     def __init__(self, url, code, msg, hdrs, fp):
  129.         self.code = code
  130.         self.msg = msg
  131.         self.hdrs = hdrs
  132.         self.fp = fp
  133.         self.filename = url
  134.         if fp is not None:
  135.             self._HTTPError__super_init(fp, hdrs, url)
  136.         
  137.  
  138.     
  139.     def __str__(self):
  140.         return 'HTTP Error %s: %s' % (self.code, self.msg)
  141.  
  142.  
  143.  
  144. class GopherError(URLError):
  145.     pass
  146.  
  147. _cut_port_re = re.compile(':\\d+$')
  148.  
  149. def request_host(request):
  150.     '''Return request-host, as defined by RFC 2965.
  151.  
  152.     Variation from RFC: returned value is lowercased, for convenient
  153.     comparison.
  154.  
  155.     '''
  156.     url = request.get_full_url()
  157.     host = urlparse.urlparse(url)[1]
  158.     if host == '':
  159.         host = request.get_header('Host', '')
  160.     
  161.     host = _cut_port_re.sub('', host, 1)
  162.     return host.lower()
  163.  
  164.  
  165. class Request:
  166.     
  167.     def __init__(self, url, data = None, headers = { }, origin_req_host = None, unverifiable = False):
  168.         self._Request__original = unwrap(url)
  169.         self.type = None
  170.         self.host = None
  171.         self.port = None
  172.         self.data = data
  173.         self.headers = { }
  174.         for key, value in headers.items():
  175.             self.add_header(key, value)
  176.         
  177.         self.unredirected_hdrs = { }
  178.         if origin_req_host is None:
  179.             origin_req_host = request_host(self)
  180.         
  181.         self.origin_req_host = origin_req_host
  182.         self.unverifiable = unverifiable
  183.  
  184.     
  185.     def __getattr__(self, attr):
  186.         if attr[:12] == '_Request__r_':
  187.             name = attr[12:]
  188.             if hasattr(Request, 'get_' + name):
  189.                 getattr(self, 'get_' + name)()
  190.                 return getattr(self, attr)
  191.             
  192.         
  193.         raise AttributeError, attr
  194.  
  195.     
  196.     def get_method(self):
  197.         if self.has_data():
  198.             return 'POST'
  199.         else:
  200.             return 'GET'
  201.  
  202.     
  203.     def add_data(self, data):
  204.         self.data = data
  205.  
  206.     
  207.     def has_data(self):
  208.         return self.data is not None
  209.  
  210.     
  211.     def get_data(self):
  212.         return self.data
  213.  
  214.     
  215.     def get_full_url(self):
  216.         return self._Request__original
  217.  
  218.     
  219.     def get_type(self):
  220.         if self.type is None:
  221.             (self.type, self._Request__r_type) = splittype(self._Request__original)
  222.             if self.type is None:
  223.                 raise ValueError, 'unknown url type: %s' % self._Request__original
  224.             
  225.         
  226.         return self.type
  227.  
  228.     
  229.     def get_host(self):
  230.         if self.host is None:
  231.             (self.host, self._Request__r_host) = splithost(self._Request__r_type)
  232.             if self.host:
  233.                 self.host = unquote(self.host)
  234.             
  235.         
  236.         return self.host
  237.  
  238.     
  239.     def get_selector(self):
  240.         return self._Request__r_host
  241.  
  242.     
  243.     def set_proxy(self, host, type):
  244.         self.host = host
  245.         self.type = type
  246.         self._Request__r_host = self._Request__original
  247.  
  248.     
  249.     def get_origin_req_host(self):
  250.         return self.origin_req_host
  251.  
  252.     
  253.     def is_unverifiable(self):
  254.         return self.unverifiable
  255.  
  256.     
  257.     def add_header(self, key, val):
  258.         self.headers[key.capitalize()] = val
  259.  
  260.     
  261.     def add_unredirected_header(self, key, val):
  262.         self.unredirected_hdrs[key.capitalize()] = val
  263.  
  264.     
  265.     def has_header(self, header_name):
  266.         if not header_name in self.headers:
  267.             pass
  268.         return header_name in self.unredirected_hdrs
  269.  
  270.     
  271.     def get_header(self, header_name, default = None):
  272.         return self.headers.get(header_name, self.unredirected_hdrs.get(header_name, default))
  273.  
  274.     
  275.     def header_items(self):
  276.         hdrs = self.unredirected_hdrs.copy()
  277.         hdrs.update(self.headers)
  278.         return hdrs.items()
  279.  
  280.  
  281.  
  282. class OpenerDirector:
  283.     
  284.     def __init__(self):
  285.         client_version = 'Python-urllib/%s' % __version__
  286.         self.addheaders = [
  287.             ('User-agent', client_version)]
  288.         self.handlers = []
  289.         self.handle_open = { }
  290.         self.handle_error = { }
  291.         self.process_response = { }
  292.         self.process_request = { }
  293.  
  294.     
  295.     def add_handler(self, handler):
  296.         added = False
  297.         for meth in dir(handler):
  298.             if meth in ('redirect_request', 'do_open', 'proxy_open'):
  299.                 continue
  300.             
  301.             i = meth.find('_')
  302.             protocol = meth[:i]
  303.             condition = meth[i + 1:]
  304.             if condition.startswith('error'):
  305.                 j = condition.find('_') + i + 1
  306.                 kind = meth[j + 1:]
  307.                 
  308.                 try:
  309.                     kind = int(kind)
  310.                 except ValueError:
  311.                     pass
  312.  
  313.                 lookup = self.handle_error.get(protocol, { })
  314.                 self.handle_error[protocol] = lookup
  315.             elif condition == 'open':
  316.                 kind = protocol
  317.                 lookup = self.handle_open
  318.             elif condition == 'response':
  319.                 kind = protocol
  320.                 lookup = self.process_response
  321.             elif condition == 'request':
  322.                 kind = protocol
  323.                 lookup = self.process_request
  324.             
  325.             handlers = lookup.setdefault(kind, [])
  326.             if handlers:
  327.                 bisect.insort(handlers, handler)
  328.             else:
  329.                 handlers.append(handler)
  330.             added = True
  331.         
  332.         if added:
  333.             bisect.insort(self.handlers, handler)
  334.             handler.add_parent(self)
  335.         
  336.  
  337.     
  338.     def close(self):
  339.         pass
  340.  
  341.     
  342.     def _call_chain(self, chain, kind, meth_name, *args):
  343.         handlers = chain.get(kind, ())
  344.         for handler in handlers:
  345.             func = getattr(handler, meth_name)
  346.             result = func(*args)
  347.             if result is not None:
  348.                 return result
  349.                 continue
  350.         
  351.  
  352.     
  353.     def open(self, fullurl, data = None):
  354.         if isinstance(fullurl, basestring):
  355.             req = Request(fullurl, data)
  356.         else:
  357.             req = fullurl
  358.             if data is not None:
  359.                 req.add_data(data)
  360.             
  361.         protocol = req.get_type()
  362.         meth_name = protocol + '_request'
  363.         for processor in self.process_request.get(protocol, []):
  364.             meth = getattr(processor, meth_name)
  365.             req = meth(req)
  366.         
  367.         response = self._open(req, data)
  368.         meth_name = protocol + '_response'
  369.         for processor in self.process_response.get(protocol, []):
  370.             meth = getattr(processor, meth_name)
  371.             response = meth(req, response)
  372.         
  373.         return response
  374.  
  375.     
  376.     def _open(self, req, data = None):
  377.         result = self._call_chain(self.handle_open, 'default', 'default_open', req)
  378.         if result:
  379.             return result
  380.         
  381.         protocol = req.get_type()
  382.         result = self._call_chain(self.handle_open, protocol, protocol + '_open', req)
  383.         if result:
  384.             return result
  385.         
  386.         return self._call_chain(self.handle_open, 'unknown', 'unknown_open', req)
  387.  
  388.     
  389.     def error(self, proto, *args):
  390.         if proto in ('http', 'https'):
  391.             dict = self.handle_error['http']
  392.             proto = args[2]
  393.             meth_name = 'http_error_%s' % proto
  394.             http_err = 1
  395.             orig_args = args
  396.         else:
  397.             dict = self.handle_error
  398.             meth_name = proto + '_error'
  399.             http_err = 0
  400.         args = (dict, proto, meth_name) + args
  401.         result = self._call_chain(*args)
  402.         if result:
  403.             return result
  404.         
  405.         if http_err:
  406.             args = (dict, 'default', 'http_error_default') + orig_args
  407.             return self._call_chain(*args)
  408.         
  409.  
  410.  
  411.  
  412. def build_opener(*handlers):
  413.     '''Create an opener object from a list of handlers.
  414.  
  415.     The opener will use several default handlers, including support
  416.     for HTTP and FTP.
  417.  
  418.     If any of the handlers passed as arguments are subclasses of the
  419.     default handlers, the default handlers will not be used.
  420.     '''
  421.     import types
  422.     
  423.     def isclass(obj):
  424.         if not isinstance(obj, types.ClassType):
  425.             pass
  426.         return hasattr(obj, '__bases__')
  427.  
  428.     opener = OpenerDirector()
  429.     default_classes = [
  430.         ProxyHandler,
  431.         UnknownHandler,
  432.         HTTPHandler,
  433.         HTTPDefaultErrorHandler,
  434.         HTTPRedirectHandler,
  435.         FTPHandler,
  436.         FileHandler,
  437.         HTTPErrorProcessor]
  438.     if hasattr(httplib, 'HTTPS'):
  439.         default_classes.append(HTTPSHandler)
  440.     
  441.     skip = []
  442.     for klass in default_classes:
  443.         for check in handlers:
  444.             if isclass(check):
  445.                 if issubclass(check, klass):
  446.                     skip.append(klass)
  447.                 
  448.             issubclass(check, klass)
  449.             if isinstance(check, klass):
  450.                 skip.append(klass)
  451.                 continue
  452.         
  453.     
  454.     for klass in skip:
  455.         default_classes.remove(klass)
  456.     
  457.     for klass in default_classes:
  458.         opener.add_handler(klass())
  459.     
  460.     for h in handlers:
  461.         if isclass(h):
  462.             h = h()
  463.         
  464.         opener.add_handler(h)
  465.     
  466.     return opener
  467.  
  468.  
  469. class BaseHandler:
  470.     handler_order = 500
  471.     
  472.     def add_parent(self, parent):
  473.         self.parent = parent
  474.  
  475.     
  476.     def close(self):
  477.         pass
  478.  
  479.     
  480.     def __lt__(self, other):
  481.         if not hasattr(other, 'handler_order'):
  482.             return True
  483.         
  484.         return self.handler_order < other.handler_order
  485.  
  486.  
  487.  
  488. class HTTPErrorProcessor(BaseHandler):
  489.     '''Process HTTP error responses.'''
  490.     handler_order = 1000
  491.     
  492.     def http_response(self, request, response):
  493.         code = response.code
  494.         msg = response.msg
  495.         hdrs = response.info()
  496.         if code not in (200, 206):
  497.             response = self.parent.error('http', request, response, code, msg, hdrs)
  498.         
  499.         return response
  500.  
  501.     https_response = http_response
  502.  
  503.  
  504. class HTTPDefaultErrorHandler(BaseHandler):
  505.     
  506.     def http_error_default(self, req, fp, code, msg, hdrs):
  507.         raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
  508.  
  509.  
  510.  
  511. class HTTPRedirectHandler(BaseHandler):
  512.     max_repeats = 4
  513.     max_redirections = 10
  514.     
  515.     def redirect_request(self, req, fp, code, msg, headers, newurl):
  516.         """Return a Request or None in response to a redirect.
  517.  
  518.         This is called by the http_error_30x methods when a
  519.         redirection response is received.  If a redirection should
  520.         take place, return a new Request to allow http_error_30x to
  521.         perform the redirect.  Otherwise, raise HTTPError if no-one
  522.         else should try to handle this url.  Return None if you can't
  523.         but another Handler might.
  524.         """
  525.         m = req.get_method()
  526.         if (code in (301, 302, 303, 307) or m in ('GET', 'HEAD') or code in (301, 302, 303)) and m == 'POST':
  527.             newurl = newurl.replace(' ', '%20')
  528.             return Request(newurl, headers = req.headers, origin_req_host = req.get_origin_req_host(), unverifiable = True)
  529.         else:
  530.             raise HTTPError(req.get_full_url(), code, msg, headers, fp)
  531.  
  532.     
  533.     def http_error_302(self, req, fp, code, msg, headers):
  534.         if 'location' in headers:
  535.             newurl = headers.getheaders('location')[0]
  536.         elif 'uri' in headers:
  537.             newurl = headers.getheaders('uri')[0]
  538.         else:
  539.             return None
  540.         newurl = urlparse.urljoin(req.get_full_url(), newurl)
  541.         new = self.redirect_request(req, fp, code, msg, headers, newurl)
  542.         if new is None:
  543.             return None
  544.         
  545.         if hasattr(req, 'redirect_dict'):
  546.             visited = new.redirect_dict = req.redirect_dict
  547.             if visited.get(newurl, 0) >= self.max_repeats or len(visited) >= self.max_redirections:
  548.                 raise HTTPError(req.get_full_url(), code, self.inf_msg + msg, headers, fp)
  549.             
  550.         else:
  551.             visited = new.redirect_dict = req.redirect_dict = { }
  552.         visited[newurl] = visited.get(newurl, 0) + 1
  553.         fp.read()
  554.         fp.close()
  555.         return self.parent.open(new)
  556.  
  557.     http_error_301 = http_error_303 = http_error_307 = http_error_302
  558.     inf_msg = 'The HTTP server returned a redirect error that would lead to an infinite loop.\nThe last 30x error message was:\n'
  559.  
  560.  
  561. def _parse_proxy(proxy):
  562.     """Return (scheme, user, password, host/port) given a URL or an authority.
  563.  
  564.     If a URL is supplied, it must have an authority (host:port) component.
  565.     According to RFC 3986, having an authority component means the URL must
  566.     have two slashes after the scheme:
  567.  
  568.     >>> _parse_proxy('file:/ftp.example.com/')
  569.     Traceback (most recent call last):
  570.     ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
  571.  
  572.     The first three items of the returned tuple may be None.
  573.  
  574.     Examples of authority parsing:
  575.  
  576.     >>> _parse_proxy('proxy.example.com')
  577.     (None, None, None, 'proxy.example.com')
  578.     >>> _parse_proxy('proxy.example.com:3128')
  579.     (None, None, None, 'proxy.example.com:3128')
  580.  
  581.     The authority component may optionally include userinfo (assumed to be
  582.     username:password):
  583.  
  584.     >>> _parse_proxy('joe:password@proxy.example.com')
  585.     (None, 'joe', 'password', 'proxy.example.com')
  586.     >>> _parse_proxy('joe:password@proxy.example.com:3128')
  587.     (None, 'joe', 'password', 'proxy.example.com:3128')
  588.  
  589.     Same examples, but with URLs instead:
  590.  
  591.     >>> _parse_proxy('http://proxy.example.com/')
  592.     ('http', None, None, 'proxy.example.com')
  593.     >>> _parse_proxy('http://proxy.example.com:3128/')
  594.     ('http', None, None, 'proxy.example.com:3128')
  595.     >>> _parse_proxy('http://joe:password@proxy.example.com/')
  596.     ('http', 'joe', 'password', 'proxy.example.com')
  597.     >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
  598.     ('http', 'joe', 'password', 'proxy.example.com:3128')
  599.  
  600.     Everything after the authority is ignored:
  601.  
  602.     >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
  603.     ('ftp', 'joe', 'password', 'proxy.example.com')
  604.  
  605.     Test for no trailing '/' case:
  606.  
  607.     >>> _parse_proxy('http://joe:password@proxy.example.com')
  608.     ('http', 'joe', 'password', 'proxy.example.com')
  609.  
  610.     """
  611.     (scheme, r_scheme) = splittype(proxy)
  612.     if not r_scheme.startswith('/'):
  613.         scheme = None
  614.         authority = proxy
  615.     elif not r_scheme.startswith('//'):
  616.         raise ValueError('proxy URL with no authority: %r' % proxy)
  617.     
  618.     end = r_scheme.find('/', 2)
  619.     if end == -1:
  620.         end = None
  621.     
  622.     authority = r_scheme[2:end]
  623.     (userinfo, hostport) = splituser(authority)
  624.     if userinfo is not None:
  625.         (user, password) = splitpasswd(userinfo)
  626.     else:
  627.         user = None
  628.         password = None
  629.     return (scheme, user, password, hostport)
  630.  
  631.  
  632. class ProxyHandler(BaseHandler):
  633.     handler_order = 100
  634.     
  635.     def __init__(self, proxies = None):
  636.         if proxies is None:
  637.             proxies = getproxies()
  638.         
  639.         if not hasattr(proxies, 'has_key'):
  640.             raise AssertionError, 'proxies must be a mapping'
  641.         self.proxies = proxies
  642.         for type, url in proxies.items():
  643.             setattr(self, '%s_open' % type, (lambda r, proxy = url, type = type, meth = self.proxy_open: meth(r, proxy, type)))
  644.         
  645.  
  646.     
  647.     def proxy_open(self, req, proxy, type):
  648.         orig_type = req.get_type()
  649.         (proxy_type, user, password, hostport) = _parse_proxy(proxy)
  650.         if proxy_type is None:
  651.             proxy_type = orig_type
  652.         
  653.         if user and password:
  654.             user_pass = '%s:%s' % (unquote(user), unquote(password))
  655.             creds = base64.b64encode(user_pass).strip()
  656.             req.add_header('Proxy-authorization', 'Basic ' + creds)
  657.         
  658.         hostport = unquote(hostport)
  659.         req.set_proxy(hostport, proxy_type)
  660.         if orig_type == proxy_type:
  661.             return None
  662.         else:
  663.             return self.parent.open(req)
  664.  
  665.  
  666.  
  667. class HTTPPasswordMgr:
  668.     
  669.     def __init__(self):
  670.         self.passwd = { }
  671.  
  672.     
  673.     def add_password(self, realm, uri, user, passwd):
  674.         if isinstance(uri, basestring):
  675.             uri = [
  676.                 uri]
  677.         
  678.         if realm not in self.passwd:
  679.             self.passwd[realm] = { }
  680.         
  681.         for default_port in (True, False):
  682.             reduced_uri = []([ self.reduce_uri(u, default_port) for u in uri ])
  683.             self.passwd[realm][reduced_uri] = (user, passwd)
  684.         
  685.  
  686.     
  687.     def find_user_password(self, realm, authuri):
  688.         domains = self.passwd.get(realm, { })
  689.         for default_port in (True, False):
  690.             reduced_authuri = self.reduce_uri(authuri, default_port)
  691.             for uris, authinfo in domains.iteritems():
  692.                 for uri in uris:
  693.                     if self.is_suburi(uri, reduced_authuri):
  694.                         return authinfo
  695.                         continue
  696.                 
  697.             
  698.         
  699.         return (None, None)
  700.  
  701.     
  702.     def reduce_uri(self, uri, default_port = True):
  703.         '''Accept authority or URI and extract only the authority and path.'''
  704.         parts = urlparse.urlsplit(uri)
  705.         if parts[1]:
  706.             scheme = parts[0]
  707.             authority = parts[1]
  708.             if not parts[2]:
  709.                 pass
  710.             path = '/'
  711.         else:
  712.             scheme = None
  713.             authority = uri
  714.             path = '/'
  715.         (host, port) = splitport(authority)
  716.         if default_port and port is None and scheme is not None:
  717.             dport = {
  718.                 'http': 80,
  719.                 'https': 443 }.get(scheme)
  720.             if dport is not None:
  721.                 authority = '%s:%d' % (host, dport)
  722.             
  723.         
  724.         return (authority, path)
  725.  
  726.     
  727.     def is_suburi(self, base, test):
  728.         '''Check if test is below base in a URI tree
  729.  
  730.         Both args must be URIs in reduced form.
  731.         '''
  732.         if base == test:
  733.             return True
  734.         
  735.         if base[0] != test[0]:
  736.             return False
  737.         
  738.         common = posixpath.commonprefix((base[1], test[1]))
  739.         if len(common) == len(base[1]):
  740.             return True
  741.         
  742.         return False
  743.  
  744.  
  745.  
  746. class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
  747.     
  748.     def find_user_password(self, realm, authuri):
  749.         (user, password) = HTTPPasswordMgr.find_user_password(self, realm, authuri)
  750.         if user is not None:
  751.             return (user, password)
  752.         
  753.         return HTTPPasswordMgr.find_user_password(self, None, authuri)
  754.  
  755.  
  756.  
  757. class AbstractBasicAuthHandler:
  758.     rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I)
  759.     
  760.     def __init__(self, password_mgr = None):
  761.         if password_mgr is None:
  762.             password_mgr = HTTPPasswordMgr()
  763.         
  764.         self.passwd = password_mgr
  765.         self.add_password = self.passwd.add_password
  766.  
  767.     
  768.     def http_error_auth_reqed(self, authreq, host, req, headers):
  769.         authreq = headers.get(authreq, None)
  770.         if authreq:
  771.             mo = AbstractBasicAuthHandler.rx.search(authreq)
  772.             if mo:
  773.                 (scheme, realm) = mo.groups()
  774.                 if scheme.lower() == 'basic':
  775.                     return self.retry_http_basic_auth(host, req, realm)
  776.                 
  777.             
  778.         
  779.  
  780.     
  781.     def retry_http_basic_auth(self, host, req, realm):
  782.         (user, pw) = self.passwd.find_user_password(realm, host)
  783.         if pw is not None:
  784.             raw = '%s:%s' % (user, pw)
  785.             auth = 'Basic %s' % base64.b64encode(raw).strip()
  786.             if req.headers.get(self.auth_header, None) == auth:
  787.                 return None
  788.             
  789.             req.add_header(self.auth_header, auth)
  790.             return self.parent.open(req)
  791.         else:
  792.             return None
  793.  
  794.  
  795.  
  796. class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  797.     auth_header = 'Authorization'
  798.     
  799.     def http_error_401(self, req, fp, code, msg, headers):
  800.         url = req.get_full_url()
  801.         return self.http_error_auth_reqed('www-authenticate', url, req, headers)
  802.  
  803.  
  804.  
  805. class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  806.     auth_header = 'Proxy-authorization'
  807.     
  808.     def http_error_407(self, req, fp, code, msg, headers):
  809.         authority = req.get_host()
  810.         return self.http_error_auth_reqed('proxy-authenticate', authority, req, headers)
  811.  
  812.  
  813.  
  814. def randombytes(n):
  815.     '''Return n random bytes.'''
  816.     pass
  817.  
  818.  
  819. class AbstractDigestAuthHandler:
  820.     
  821.     def __init__(self, passwd = None):
  822.         if passwd is None:
  823.             passwd = HTTPPasswordMgr()
  824.         
  825.         self.passwd = passwd
  826.         self.add_password = self.passwd.add_password
  827.         self.retried = 0
  828.         self.nonce_count = 0
  829.  
  830.     
  831.     def reset_retry_count(self):
  832.         self.retried = 0
  833.  
  834.     
  835.     def http_error_auth_reqed(self, auth_header, host, req, headers):
  836.         authreq = headers.get(auth_header, None)
  837.         if authreq:
  838.             scheme = authreq.split()[0]
  839.             if scheme.lower() == 'digest':
  840.                 return self.retry_http_digest_auth(req, authreq)
  841.             
  842.         
  843.  
  844.     
  845.     def retry_http_digest_auth(self, req, auth):
  846.         (token, challenge) = auth.split(' ', 1)
  847.         chal = parse_keqv_list(parse_http_list(challenge))
  848.         auth = self.get_authorization(req, chal)
  849.         if auth:
  850.             auth_val = 'Digest %s' % auth
  851.             if req.headers.get(self.auth_header, None) == auth_val:
  852.                 return None
  853.             
  854.             req.add_unredirected_header(self.auth_header, auth_val)
  855.             resp = self.parent.open(req)
  856.             return resp
  857.         
  858.  
  859.     
  860.     def get_cnonce(self, nonce):
  861.         dig = hashlib.sha1('%s:%s:%s:%s' % (self.nonce_count, nonce, time.ctime(), randombytes(8))).hexdigest()
  862.         return dig[:16]
  863.  
  864.     
  865.     def get_authorization(self, req, chal):
  866.         
  867.         try:
  868.             realm = chal['realm']
  869.             nonce = chal['nonce']
  870.             qop = chal.get('qop')
  871.             algorithm = chal.get('algorithm', 'MD5')
  872.             opaque = chal.get('opaque', None)
  873.         except KeyError:
  874.             return None
  875.  
  876.         (H, KD) = self.get_algorithm_impls(algorithm)
  877.         if H is None:
  878.             return None
  879.         
  880.         (user, pw) = self.passwd.find_user_password(realm, req.get_full_url())
  881.         if user is None:
  882.             return None
  883.         
  884.         if req.has_data():
  885.             entdig = self.get_entity_digest(req.get_data(), chal)
  886.         else:
  887.             entdig = None
  888.         A1 = '%s:%s:%s' % (user, realm, pw)
  889.         A2 = '%s:%s' % (req.get_method(), req.get_selector())
  890.         if qop == 'auth':
  891.             self.nonce_count += 1
  892.             ncvalue = '%08x' % self.nonce_count
  893.             cnonce = self.get_cnonce(nonce)
  894.             noncebit = '%s:%s:%s:%s:%s' % (nonce, ncvalue, cnonce, qop, H(A2))
  895.             respdig = KD(H(A1), noncebit)
  896.         elif qop is None:
  897.             respdig = KD(H(A1), '%s:%s' % (nonce, H(A2)))
  898.         
  899.         base = 'username="%s", realm="%s", nonce="%s", uri="%s", response="%s"' % (user, realm, nonce, req.get_selector(), respdig)
  900.         if opaque:
  901.             base += ', opaque="%s"' % opaque
  902.         
  903.         if entdig:
  904.             base += ', digest="%s"' % entdig
  905.         
  906.         base += ', algorithm="%s"' % algorithm
  907.         if qop:
  908.             base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
  909.         
  910.         return base
  911.  
  912.     
  913.     def get_algorithm_impls(self, algorithm):
  914.         if algorithm == 'MD5':
  915.             
  916.             H = lambda x: hashlib.md5(x).hexdigest()
  917.         elif algorithm == 'SHA':
  918.             
  919.             H = lambda x: hashlib.sha1(x).hexdigest()
  920.         
  921.         
  922.         KD = lambda s, d: H('%s:%s' % (s, d))
  923.         return (H, KD)
  924.  
  925.     
  926.     def get_entity_digest(self, data, chal):
  927.         pass
  928.  
  929.  
  930.  
  931. class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  932.     '''An authentication protocol defined by RFC 2069
  933.  
  934.     Digest authentication improves on basic authentication because it
  935.     does not transmit passwords in the clear.
  936.     '''
  937.     auth_header = 'Authorization'
  938.     handler_order = 490
  939.     
  940.     def http_error_401(self, req, fp, code, msg, headers):
  941.         host = urlparse.urlparse(req.get_full_url())[1]
  942.         retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
  943.         self.reset_retry_count()
  944.         return retry
  945.  
  946.  
  947.  
  948. class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  949.     auth_header = 'Proxy-Authorization'
  950.     handler_order = 490
  951.     
  952.     def http_error_407(self, req, fp, code, msg, headers):
  953.         host = req.get_host()
  954.         retry = self.http_error_auth_reqed('proxy-authenticate', host, req, headers)
  955.         self.reset_retry_count()
  956.         return retry
  957.  
  958.  
  959.  
  960. class AbstractHTTPHandler(BaseHandler):
  961.     
  962.     def __init__(self, debuglevel = 0):
  963.         self._debuglevel = debuglevel
  964.  
  965.     
  966.     def set_http_debuglevel(self, level):
  967.         self._debuglevel = level
  968.  
  969.     
  970.     def do_request_(self, request):
  971.         host = request.get_host()
  972.         if not host:
  973.             raise URLError('no host given')
  974.         
  975.         if request.has_data():
  976.             data = request.get_data()
  977.             if not request.has_header('Content-type'):
  978.                 request.add_unredirected_header('Content-type', 'application/x-www-form-urlencoded')
  979.             
  980.             if not request.has_header('Content-length'):
  981.                 request.add_unredirected_header('Content-length', '%d' % len(data))
  982.             
  983.         
  984.         (scheme, sel) = splittype(request.get_selector())
  985.         (sel_host, sel_path) = splithost(sel)
  986.         if not request.has_header('Host'):
  987.             if not sel_host:
  988.                 pass
  989.             request.add_unredirected_header('Host', host)
  990.         
  991.         for name, value in self.parent.addheaders:
  992.             name = name.capitalize()
  993.             if not request.has_header(name):
  994.                 request.add_unredirected_header(name, value)
  995.                 continue
  996.         
  997.         return request
  998.  
  999.     
  1000.     def do_open(self, http_class, req):
  1001.         '''Return an addinfourl object for the request, using http_class.
  1002.  
  1003.         http_class must implement the HTTPConnection API from httplib.
  1004.         The addinfourl return value is a file-like object.  It also
  1005.         has methods and attributes including:
  1006.             - info(): return a mimetools.Message object for the headers
  1007.             - geturl(): return the original request URL
  1008.             - code: HTTP status code
  1009.         '''
  1010.         host = req.get_host()
  1011.         if not host:
  1012.             raise URLError('no host given')
  1013.         
  1014.         h = http_class(host)
  1015.         h.set_debuglevel(self._debuglevel)
  1016.         headers = dict(req.headers)
  1017.         headers.update(req.unredirected_hdrs)
  1018.         headers['Connection'] = 'close'
  1019.         headers = dict((lambda .0: for name, val in .0:
  1020. (name.title(), val))(headers.items()))
  1021.         
  1022.         try:
  1023.             h.request(req.get_method(), req.get_selector(), req.data, headers)
  1024.             r = h.getresponse()
  1025.         except socket.error:
  1026.             err = None
  1027.             raise URLError(err)
  1028.  
  1029.         r.recv = r.read
  1030.         fp = socket._fileobject(r, close = True)
  1031.         resp = addinfourl(fp, r.msg, req.get_full_url())
  1032.         resp.code = r.status
  1033.         resp.msg = r.reason
  1034.         return resp
  1035.  
  1036.  
  1037.  
  1038. class HTTPHandler(AbstractHTTPHandler):
  1039.     
  1040.     def http_open(self, req):
  1041.         return self.do_open(httplib.HTTPConnection, req)
  1042.  
  1043.     http_request = AbstractHTTPHandler.do_request_
  1044.  
  1045. if hasattr(httplib, 'HTTPS'):
  1046.     
  1047.     class HTTPSHandler(AbstractHTTPHandler):
  1048.         
  1049.         def https_open(self, req):
  1050.             return self.do_open(httplib.HTTPSConnection, req)
  1051.  
  1052.         https_request = AbstractHTTPHandler.do_request_
  1053.  
  1054.  
  1055.  
  1056. class HTTPCookieProcessor(BaseHandler):
  1057.     
  1058.     def __init__(self, cookiejar = None):
  1059.         import cookielib
  1060.         if cookiejar is None:
  1061.             cookiejar = cookielib.CookieJar()
  1062.         
  1063.         self.cookiejar = cookiejar
  1064.  
  1065.     
  1066.     def http_request(self, request):
  1067.         self.cookiejar.add_cookie_header(request)
  1068.         return request
  1069.  
  1070.     
  1071.     def http_response(self, request, response):
  1072.         self.cookiejar.extract_cookies(response, request)
  1073.         return response
  1074.  
  1075.     https_request = http_request
  1076.     https_response = http_response
  1077.  
  1078.  
  1079. class UnknownHandler(BaseHandler):
  1080.     
  1081.     def unknown_open(self, req):
  1082.         type = req.get_type()
  1083.         raise URLError('unknown url type: %s' % type)
  1084.  
  1085.  
  1086.  
  1087. def parse_keqv_list(l):
  1088.     '''Parse list of key=value strings where keys are not duplicated.'''
  1089.     parsed = { }
  1090.     for elt in l:
  1091.         (k, v) = elt.split('=', 1)
  1092.         if v[0] == '"' and v[-1] == '"':
  1093.             v = v[1:-1]
  1094.         
  1095.         parsed[k] = v
  1096.     
  1097.     return parsed
  1098.  
  1099.  
  1100. def parse_http_list(s):
  1101.     '''Parse lists as described by RFC 2068 Section 2.
  1102.  
  1103.     In particular, parse comma-separated lists where the elements of
  1104.     the list may include quoted-strings.  A quoted-string could
  1105.     contain a comma.  A non-quoted string could have quotes in the
  1106.     middle.  Neither commas nor quotes count if they are escaped.
  1107.     Only double-quotes count, not single-quotes.
  1108.     '''
  1109.     res = []
  1110.     part = ''
  1111.     escape = quote = False
  1112.     for cur in s:
  1113.         if escape:
  1114.             part += cur
  1115.             escape = False
  1116.             continue
  1117.         
  1118.         if quote:
  1119.             if cur == '\\':
  1120.                 escape = True
  1121.                 continue
  1122.             elif cur == '"':
  1123.                 quote = False
  1124.             
  1125.             part += cur
  1126.             continue
  1127.         
  1128.         if cur == ',':
  1129.             res.append(part)
  1130.             part = ''
  1131.             continue
  1132.         
  1133.         if cur == '"':
  1134.             quote = True
  1135.         
  1136.         part += cur
  1137.     
  1138.     if part:
  1139.         res.append(part)
  1140.     
  1141.     return [ part.strip() for part in res ]
  1142.  
  1143.  
  1144. class FileHandler(BaseHandler):
  1145.     
  1146.     def file_open(self, req):
  1147.         url = req.get_selector()
  1148.         if url[:2] == '//' and url[2:3] != '/':
  1149.             req.type = 'ftp'
  1150.             return self.parent.open(req)
  1151.         else:
  1152.             return self.open_local_file(req)
  1153.  
  1154.     names = None
  1155.     
  1156.     def get_names(self):
  1157.         if FileHandler.names is None:
  1158.             
  1159.             try:
  1160.                 FileHandler.names = (socket.gethostbyname('localhost'), socket.gethostbyname(socket.gethostname()))
  1161.             except socket.gaierror:
  1162.                 FileHandler.names = (socket.gethostbyname('localhost'),)
  1163.             except:
  1164.                 None<EXCEPTION MATCH>socket.gaierror
  1165.             
  1166.  
  1167.         None<EXCEPTION MATCH>socket.gaierror
  1168.         return FileHandler.names
  1169.  
  1170.     
  1171.     def open_local_file(self, req):
  1172.         import email.Utils as email
  1173.         import mimetypes
  1174.         host = req.get_host()
  1175.         file = req.get_selector()
  1176.         localfile = url2pathname(file)
  1177.         stats = os.stat(localfile)
  1178.         size = stats.st_size
  1179.         modified = email.Utils.formatdate(stats.st_mtime, usegmt = True)
  1180.         mtype = mimetypes.guess_type(file)[0]
  1181.         if not mtype:
  1182.             pass
  1183.         headers = mimetools.Message(StringIO('Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % ('text/plain', size, modified)))
  1184.         if host:
  1185.             (host, port) = splitport(host)
  1186.         
  1187.         if (not host or not port) and socket.gethostbyname(host) in self.get_names():
  1188.             return addinfourl(open(localfile, 'rb'), headers, 'file:' + file)
  1189.         
  1190.         raise URLError('file not on local host')
  1191.  
  1192.  
  1193.  
  1194. class FTPHandler(BaseHandler):
  1195.     
  1196.     def ftp_open(self, req):
  1197.         import ftplib
  1198.         import mimetypes
  1199.         host = req.get_host()
  1200.         if not host:
  1201.             raise IOError, ('ftp error', 'no host given')
  1202.         
  1203.         (host, port) = splitport(host)
  1204.         if port is None:
  1205.             port = ftplib.FTP_PORT
  1206.         else:
  1207.             port = int(port)
  1208.         (user, host) = splituser(host)
  1209.         if user:
  1210.             (user, passwd) = splitpasswd(user)
  1211.         else:
  1212.             passwd = None
  1213.         host = unquote(host)
  1214.         if not user:
  1215.             pass
  1216.         user = unquote('')
  1217.         if not passwd:
  1218.             pass
  1219.         passwd = unquote('')
  1220.         
  1221.         try:
  1222.             host = socket.gethostbyname(host)
  1223.         except socket.error:
  1224.             msg = None
  1225.             raise URLError(msg)
  1226.  
  1227.         (path, attrs) = splitattr(req.get_selector())
  1228.         dirs = path.split('/')
  1229.         dirs = map(unquote, dirs)
  1230.         dirs = dirs[:-1]
  1231.         file = dirs[-1]
  1232.         if dirs and not dirs[0]:
  1233.             dirs = dirs[1:]
  1234.         
  1235.         
  1236.         try:
  1237.             fw = self.connect_ftp(user, passwd, host, port, dirs)
  1238.             if not file or 'I':
  1239.                 pass
  1240.             type = 'D'
  1241.             for attr in attrs:
  1242.                 (attr, value) = splitvalue(attr)
  1243.                 if attr.lower() == 'type' and value in ('a', 'A', 'i', 'I', 'd', 'D'):
  1244.                     type = value.upper()
  1245.                     continue
  1246.             
  1247.             (fp, retrlen) = fw.retrfile(file, type)
  1248.             headers = ''
  1249.             mtype = mimetypes.guess_type(req.get_full_url())[0]
  1250.             if mtype:
  1251.                 headers += 'Content-type: %s\n' % mtype
  1252.             
  1253.             if retrlen is not None and retrlen >= 0:
  1254.                 headers += 'Content-length: %d\n' % retrlen
  1255.             
  1256.             sf = StringIO(headers)
  1257.             headers = mimetools.Message(sf)
  1258.             return addinfourl(fp, headers, req.get_full_url())
  1259.         except ftplib.all_errors:
  1260.             msg = None
  1261.             raise IOError, ('ftp error', msg), sys.exc_info()[2]
  1262.  
  1263.  
  1264.     
  1265.     def connect_ftp(self, user, passwd, host, port, dirs):
  1266.         fw = ftpwrapper(user, passwd, host, port, dirs)
  1267.         return fw
  1268.  
  1269.  
  1270.  
  1271. class CacheFTPHandler(FTPHandler):
  1272.     
  1273.     def __init__(self):
  1274.         self.cache = { }
  1275.         self.timeout = { }
  1276.         self.soonest = 0
  1277.         self.delay = 60
  1278.         self.max_conns = 16
  1279.  
  1280.     
  1281.     def setTimeout(self, t):
  1282.         self.delay = t
  1283.  
  1284.     
  1285.     def setMaxConns(self, m):
  1286.         self.max_conns = m
  1287.  
  1288.     
  1289.     def connect_ftp(self, user, passwd, host, port, dirs):
  1290.         key = (user, host, port, '/'.join(dirs))
  1291.         if key in self.cache:
  1292.             self.timeout[key] = time.time() + self.delay
  1293.         else:
  1294.             self.cache[key] = ftpwrapper(user, passwd, host, port, dirs)
  1295.             self.timeout[key] = time.time() + self.delay
  1296.         self.check_cache()
  1297.         return self.cache[key]
  1298.  
  1299.     
  1300.     def check_cache(self):
  1301.         t = time.time()
  1302.         if self.soonest <= t:
  1303.             for k, v in self.timeout.items():
  1304.                 if v < t:
  1305.                     self.cache[k].close()
  1306.                     del self.cache[k]
  1307.                     del self.timeout[k]
  1308.                     continue
  1309.             
  1310.         
  1311.         self.soonest = min(self.timeout.values())
  1312.         if len(self.cache) == self.max_conns:
  1313.             for k, v in self.timeout.items():
  1314.                 if v == self.soonest:
  1315.                     del self.cache[k]
  1316.                     del self.timeout[k]
  1317.                     break
  1318.                     continue
  1319.             
  1320.             self.soonest = min(self.timeout.values())
  1321.         
  1322.  
  1323.  
  1324.  
  1325. class GopherHandler(BaseHandler):
  1326.     
  1327.     def gopher_open(self, req):
  1328.         import gopherlib
  1329.         host = req.get_host()
  1330.         if not host:
  1331.             raise GopherError('no host given')
  1332.         
  1333.         host = unquote(host)
  1334.         selector = req.get_selector()
  1335.         (type, selector) = splitgophertype(selector)
  1336.         (selector, query) = splitquery(selector)
  1337.         selector = unquote(selector)
  1338.         if query:
  1339.             query = unquote(query)
  1340.             fp = gopherlib.send_query(selector, query, host)
  1341.         else:
  1342.             fp = gopherlib.send_selector(selector, host)
  1343.         return addinfourl(fp, noheaders(), req.get_full_url())
  1344.  
  1345.  
  1346.